import type { DeviceAddTreePropsType } from './typings'
import { ref, reactive } from 'vue'
import { ElDialog, ElButton, ElTree, ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import useVuexGetters from '~/hooks/useVuexGetters'

export default function DeviceAddTree(props: DeviceAddTreePropsType) {
  const store = useStore()
  const { cancel } = props
  const loadingRef = ref<boolean>()
  const loopSwitchGroupState = useVuexGetters('loopSwitchGroup', ['activeLoopGroupId'])
  const state = reactive<any>({
    treeList: [],
    checkedNodes: []
  })
  // 提交
  const handleSubmit = async () => {
    loadingRef.value = true
    if (state.checkedNodes.length === 0) {
      ElMessage({ type: 'warning', message: '请勾选数据' })
      return
    }
    const res = await store.dispatch(
      'loopSwitchGroup/SaveTaskGroupDeviceLoopPost',
      state.checkedNodes
    )
    loadingRef.value = false
    if (res?.code === 200) {
      ElMessage({ type: 'success', message: '操作成功' })
      cancel()
    }
  }
  //  回路tree
  const handleDeviceLoopTree = async () => {
    const { code, data } = await store.dispatch('loopSwitchGroup/GetDeviceLoopTreeGet')
    if (code === 200) {
      state.treeList = data
    }
  }
  //  tree选择
  const onCheck = (data: { title: string }, { checkedNodes }: any) => {
    const list: { deviceId: any; loopName: any; taskGroupId: any }[] = []
    if (checkedNodes.length > 0) {
      checkedNodes.forEach((item: any) => {
        list.push({
          deviceId: item.id,
          loopName: item.value.length > 1 ? item.value : item.title,
          taskGroupId: loopSwitchGroupState?.activeLoopGroupId?.value
        })
      })
    }
    state.checkedNodes = list
  }

  // 初始化可选分组列表
  handleDeviceLoopTree()

  return (
    <ElDialog
      width={450}
      title="选择监控箱回路"
      modelValue={props.visible}
      closeOnClickModal={false} // 点遮罩层不关弹窗
      draggable // 可拖拽
      beforeClose={cancel}
      v-slots={{
        footer: () => (
          <>
            <ElButton type="primary" loading={loadingRef.value} onClick={handleSubmit}>
              保存
            </ElButton>
            <ElButton onClick={cancel}>取消</ElButton>
          </>
        )
      }}
    >
      <ElTree
        data={state.treeList}
        props={{
          label: 'title',
          children: 'children'
        }}
        show-checkbox
        onCheck={onCheck}
      />
    </ElDialog>
  )
}
